#include "pch.h"
#include "ParticleRenderer.h"
#include "ParticleEmitter.h"
namespace mini
{

	CParticleRenderer::CParticleRenderer(CDevice* pDevice)
	: CRenderer(pDevice)
	{
		mOrder = 240;
		mRenderTypeFlag = RendererType::ParticleRenderer;
	}

	CParticleRenderer::~CParticleRenderer()
	{

	}

	void CParticleRenderer::processRenderNode(CRenderNode* pRenderNode)
	{
		auto pActor = pRenderNode->getActor();
		for (auto child : pActor->getUnits())
		{
			CMeshUnit* pMeshUnit = dynamic_cast<CMeshUnit*>(child);
			if (nullptr != pMeshUnit)
			{
				CParticleEmitter* pEmitter = dynamic_cast<CParticleEmitter*>(pActor);
				if (pEmitter->mParticelsContent.size() > 0)
				{
					CMesh* pMesh = pMeshUnit->getBuildMesh();
					D3D11_MAPPED_SUBRESOURCE mappedResource;
					HRESULT result = mpDeferredContext->Map(pMesh->getVertexBuffer(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
					if (FAILED(result))
					{
						return;
					}
					int nSize = pEmitter->mParticelsContent.size();
					// Copy the data into the vertex buffer.
					memcpy(mappedResource.pData, &pEmitter->mParticelsContent[0], (sizeof(VertexVTC) * nSize));

					// Unlock the vertex buffer.
					mpDeferredContext->Unmap(pMesh->getVertexBuffer(), 0);
					addUnit(child, pMeshUnit->getMaterialUnit(), pActor->getEntityType(), pRenderNode->getRenderLayer());
				}
			}
		}
	}
}